﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading.Tasks;

namespace TcpEchoSocketServer
{
    class Program
    {
        static void Main(string[] args)
        {
            const int BUFSIZE = 32;
            const int BACKLOG = 5;

            int port = 7;

            byte[] buffer = new byte[BUFSIZE];
            int bytesRecived;
            Socket server = null;

            try
            {
                server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                server.Bind(new IPEndPoint(IPAddress.Any, port));
                server.Listen(BACKLOG);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex.Message);
                Environment.Exit(ex.ErrorCode);               
            }



            while (true)
            {
                Socket client = null;

                try
                {
                    client = server.Accept();
                    Console.WriteLine("Handling client " + client.RemoteEndPoint);

                    int totalBytesRecived = 0;

                    while ((bytesRecived = client.Receive(buffer, 0, buffer.Length, SocketFlags.None)) > 0)
                    {
                        client.Send(buffer, 0, bytesRecived, SocketFlags.None);
                        totalBytesRecived += bytesRecived;
                    }

                    Console.WriteLine("Message sent");
                    client.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message); 
                    client.Close();
                }
            }
        }
    }
}
